import React from 'react'
import { routerRedux, Route, Router, Switch } from 'dva/router'
import Layout from './layout'
import zhCN from 'antd/lib/locale-provider/zh_CN'
import { LocaleProvider } from 'antd'
import Loadable from 'react-loadable'

const { ConnectedRouter } = routerRedux

const routerConfig = {
  '/': {
    page: () => import('./pages/photos'),
    models: ['./models/photos'],
    exact: true
  },
  '/photos': {
    page: () => import('./pages/photos'),
    models: ['./models/photos'],
  },
  '/users': {
    page: () => import('./pages/users'),
    models: ['./models/users']
  }
}


function modelNotExisted(app, model) {
  return !app._models.some(({ namespace }) => {
    console.log(namespace, model)
    return namespace === model.substring(model.lastIndexOf('/') + 1)
  })
}

function dynamicWrapper(app, models, component) {
  models.filter(model => modelNotExisted(app, model))
    .forEach(m => app.model(require(`${m}`).default))

  return Loadable({
    loader: component,
    loading: () => <div>loading....</div>
  })
}

function getRouterData(app) {
  return Object.keys(routerConfig).map(path => {
    const route = routerConfig[path]
    const component = dynamicWrapper(app, route['models'], route['page'])
    return {
      path,
      component,
      exact: !!route.exact
    }
  })
}

function RouterConfig({ history, app }) {
  const routerData = getRouterData(app)

  return (
    <LocaleProvider locale={zhCN}>
      <ConnectedRouter history={history}>
        <Layout history={history}>
          <Router history={history}>
            <Switch>
              {routerData.map(route => (
                <Route
                  key={route.path}
                  exact={route.exact}
                  path={route.path}
                  component={route.component}
                />
              ))}
            </Switch>
          </Router>
        </Layout>
      </ConnectedRouter>
    </LocaleProvider>
  )
}

export default RouterConfig
